﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sinacor.Infra.Tools.ServiceRegistration.Business
{
    public class EndPoint
    {
        #region Attributes

        private Data.EndPoint _resourceAccess;
        private object locker = new object();

        #endregion

        #region Constructor

        public EndPoint()
        {
            this._resourceAccess = new Data.EndPoint();
        }

        #endregion

        #region Methods

        public List<Entity.EndPoint> SelectEndPoint(Entity.EndPoint entity)
        {
            return _resourceAccess.SelectEndPoint(entity, true);
        }

        public Entity.EndPoint PersistEndPoint(Entity.EndPoint entity)
        {
            Entity.EndPoint endPoint = new Entity.EndPoint() { ContractName = entity.ContractName, Protocol = entity.Protocol, Service = entity.Service };
            List<Entity.EndPoint> endPoints = null;

            endPoints = _resourceAccess.SelectEndPoint(endPoint, false);

            if (endPoints.Count == 0)
            {
                endPoint = InsertEndPoint(entity);
            }
            else
            {
                endPoint = endPoints[0];

                endPoint.Protocol = entity.Protocol;
                endPoint.DateChange = entity.DateChange;
                endPoint.DataOrigin = entity.DataOrigin;
                UpdateEndPoint(endPoint);
            }

            return endPoint;
        }

        public Entity.EndPoint InsertEndPoint(Entity.EndPoint entity)
        {
            entity.EndPointId = this.GetNextEndPointId();
            return _resourceAccess.InsertEndPoint(entity);
        }

        public void UpdateEndPoint(Entity.EndPoint entity)
        {
            _resourceAccess.UpdateEndPoint(entity);
        }

        public void DeleteEndPoint(Entity.EndPoint entity)
        {
            _resourceAccess.DeleteEndPoint(entity);
        }

        public int GetNextEndPointId()
        {
            int nextId = 0;

            lock (locker)
            {
                nextId = _resourceAccess.GetNextEndPointId();
            }

            return nextId;
        }

        #endregion
    }
            }
